﻿using Microsoft.Extensions.DependencyInjection;
using MQTTnet.Protocol;
using MQTTnet.Server;
using MQTTnet;
using SBlogCore.Common.DispatchProxyIn;
using System.Reflection;
using System.Text;
using System.Text.Json;
using SBlogCore.MqttService.Proxy.Attributes;

namespace SBlogCore.MqttService.Proxy
{
    /// <summary>
    /// MQTT代理
    /// </summary>
    public class MqttDispatchProxy: GlobalDispatchProxy
    {
        protected override object? Invoke(MethodInfo? method, object?[]? args)
        {

            if (method == null) throw new Exception("方法不存在");
            if (args == null) throw new Exception("参数不能为空");
            if (args.Length>0) throw new Exception("参数有且只能有一个");
            if (ServiceProvider == null) throw new Exception("服务注册异常");
            var isAsync = method.ReturnType.BaseType == typeof(Task);
            var topic = method.GetCustomAttribute<TopicAttribute>(true);
            var topicName = "";
            if (topic != null)
            {
                topicName = topic.Value;
            }
            if (string.IsNullOrEmpty(topicName))
            {
                throw new Exception("topic 不能为空");
            }
            var server = ServiceProvider.GetService<MqttServer>()!;

            var prm = args.FirstOrDefault(); 
            if (prm is not string json)
            {
                json = JsonSerializer.Serialize(prm);
            }
            var message = new MqttApplicationMessage
            {
                Topic = topicName,
                Payload = Encoding.Default.GetBytes(json),
                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
                Retain = true  // 服务端是否保留消息。true为保留，如果有新的订阅者连接，就会立马收到该消息。
            };
            var res = server.InjectApplicationMessage(new InjectedMqttApplicationMessage(message) // 发送消息给有订阅 topic_01的客户端
            {
                SenderClientId = "Server_01"
            });
            return isAsync ? res : null;
        }
    }
}
